using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security.Permissions;
using Microsoft.VisualBasic;

namespace Code5Systems.FormMaster
{

	public partial class FormMaster : DotNetNuke.Entities.Modules.PortalModuleBase, DotNetNuke.Entities.Modules.IActionable, DotNetNuke.Entities.Modules.IPortable
	{
		
		private void PageLoad(System.Object sender, System.EventArgs e)
		{
			//If we are in Survey Mode and a Redirect rule has been set, check if the user
			//has submitted the form already. If so then apply the Redirect Rule
			//This function is disabled if the user has edit permissions as a situation may be setup where
			//the form creator could not get to the form.
			DotNetNuke.Entities.Modules.ModuleController objModuleCtlr = new DotNetNuke.Entities.Modules.ModuleController();
			
			ModulePermissionCollection perCol = new ModulePermissionCollection(objModuleCtlr.GetModule(this.ModuleId));
			if ((!ModulePermissionController.HasModulePermission(perCol, "Edit")) && _objFormSettings.RedirectType != "N" && _objFormSettings.InSurveyMode)
			{
				if (UserId > 0)
				{
					if (_objFormCtl.HasUserPosted(ModuleId, UserId))
					{
						DoRedirect();
					}
				}
				
				if (Utility.GetCookieValue(Utility.GetValidControlID(_objFormInfo.FormName)) == "1")
				{
					DoRedirect();
				}
			}
			
			//Was the from posted
			int qsModuleId = Null.NullInteger;
			if (Information.IsNumeric(Request.QueryString["fmmid"]))
			{
				qsModuleId = int.Parse(Request.QueryString["fmmid"]);
			}
			
			if (Information.IsNumeric(Request.QueryString["fdid"]))
			{
				_formDataId = int.Parse(Request.QueryString["fdid"]);
			}
			
			if (Request.QueryString["sbmt"] == "1" && qsModuleId == ModuleId)
			{
				this.ShowThankYouPage();
			}
			else
			{
				string strWizardStyle = string.Empty;
				if (!string.IsNullOrEmpty(_objFormSettings.TableWidth))
				{
					strWizardStyle += string.Format("width: {0};", Unit.Parse(_objFormSettings.TableWidth).ToString());
				}
				
				switch (_objFormSettings.TableAlignment)
				{
					case HorizontalAlign.Left:
						strWizardStyle += "margin: 0px auto 0px 0px;";
						break;
					case HorizontalAlign.Right:
						strWizardStyle += "margin: 0px 0px 0px auto;";
						break;
					case HorizontalAlign.Center:
						strWizardStyle += "margin: 0px auto;";
						break;
				}
				
				//if (!string.IsNullOrEmpty(strWizardStyle))
				//{
				//	formWizardCtrl.Attributes.Add("style", strWizardStyle);
				//}
				
				if (!this.Page.IsPostBack)
				{
					_objFormCtl.FormInfo.CurrentPage = _objFormCtl.Pages[0];
					_xDoc = XDocument.Parse(_objFormCtl.FormInfo.CurrentPage.PageData);
					if (_objFormCtl.Pages.Count > 1)
					{
						//formWizardCtrl.ActiveStepIndex = 0;
					}

					if (_objFormSettings.ResponsiveLayout)
					{
						BindDataRwd();
					}
					else
					{
						BindData();
					}
				}
			}
		}
		
		private void SubmitClick(object sender, System.Web.UI.WebControls.CommandEventArgs e)
		{
			string strEmailSendTo = default(string);
			string strEmailSendFrom = default(string);
			_oFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
			
			_userId = this.UserId;
			
			if (HttpContext.Current.User.Identity.IsAuthenticated)
			{
				IEnumerable<HtmlInputHidden> controls = Utility.GetChildsRecursive(this.pnlForm).OfType<HtmlInputHidden>();
				foreach (HtmlInputHidden ctl in controls)
				{
					if (ctl.ID.ToLower() == "datarecordid")
					{
						int.TryParse(ctl.Value, out _formDataId);
						break;
					}
				}
			}
			
			RegisterUser();
			
			if (this._postResult == Code5Systems.FormMaster.Business.FormPostResult.FailedRegistration)
			{
				return;
			}
			
			//Get the results of the form submission
			_objResultsXmlDoc = _oFormDataCtl.GetFormResults(ModuleId, this.pnlForm, this.ControlPath, _disabledValidators, PortalId, _userId, _formDataId);
			
			//Get the FormDataId
			XAttribute xDataId = default(XAttribute);
			xDataId = _objResultsXmlDoc.Root.Attribute("FormDataID");
			if (xDataId != null)
			{
				_formDataId = int.Parse(xDataId.Value);
			}
			
			IEnumerable<XElement> xExcludeLinks = _objResultsXmlDoc.Descendants("Answers").Where(x => x.AttributeExists("ExcludeLink")).ToList();
			foreach (XElement answer in xExcludeLinks)
			{
				answer.Remove();
			}
			
			if (((Code5Systems.FormMaster.Business.FormInfo.EmailActionNone) _objFormInfo.EmailSendAction) == Code5Systems.FormMaster.Business.FormInfo.EmailActionNone.None)
			{
				_bSendMail = false;
			}
			
			if (_bSendMail & _postResult == Code5Systems.FormMaster.Business.FormPostResult.Success)
			{
				//Set the bSendMail value and get the TO: and FROM: addresses
				strEmailSendTo = GetEmailSendtoAddress();
				strEmailSendFrom = GetEmailSendFromAddress();
				SendFormEmail(strEmailSendTo, strEmailSendFrom, _objResultsXmlDoc);
			}
			
			if (_postResult == Code5Systems.FormMaster.Business.FormPostResult.Success)
			{
				//Check if we are so send the Auto Responder Message
				if (_objFormSettings.SendAutoResponder)
				{
					SendAutoResponder(_objResultsXmlDoc);
				}
				
				//If in Survey Mode set the Cookie using the Form Namte
				if (_objFormSettings.InSurveyMode)
				{
					Utility.SetCookie(Utility.GetValidControlID(_objFormInfo.FormName), "1", DateTime.MaxValue);
				}
				
				DoRedirect();
			}
			else
			{
				//If email failed prevent the user form submitting the form again
				if (_postResult == Code5Systems.FormMaster.Business.FormPostResult.FailedEmail)
				{
					DisableCommandControls(phForm);
				}
			}
		}
	}
}


